#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define EXIT_ERROR(m)       \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
#define NAME "fifo"
class NamePipe
{
public:
    NamePipe(const std::string &path, const std::string &name)
        : _path(path),
          _name(name)
    {
        _fifoname = _path + "/" + _name;
    }
    // 创建命名管道
    void Create()
    {
        umask(0);
        int ret = mkfifo(_fifoname.c_str(), 0666);
        if (ret < 0)
        {
            EXIT_ERROR("mkfifo");
        }
    }

    ~NamePipe()
    {
        int ret = unlink(_fifoname.c_str());
        if (ret < 0)
        {
            EXIT_ERROR("unlink");
        }
        std::cout<<"unlink true"<<std::endl;
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

//对文件进行操作
class FileOper
{
public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path),
          _name(name),
          _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    //以只读的方式打开文件
    void OpenReadFile()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            EXIT_ERROR("open");
        }
        std::cout<<"server:"<<std::endl;
    }
    //以只写的方式打开文件
    void OpenWriteFile()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            EXIT_ERROR("open");
        }
        std::cout<<"client"<<std::endl;
    }
    //读文件
    void Read()
    {
        while (true)
        {
            char buff[1024];
            size_t n = read(_fd, buff, sizeof(buff) - 1);
            if (n > 0)
            {
                buff[n] = 0;
                std::cout << "server :" << buff << std::endl;
            }
            else if(n==0)//当写进程关闭时，读也会关闭
            {
                std::cerr<<"读取内容为0"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"读取失败"<<std::endl;
                break;
            }
        }
    }
    //写操作
    void Write()
    {
        std::string buff;
        while (true)
        {
            getline(std::cin, buff);
            write(_fd, buff.c_str(), buff.size());
        }
    }
    void Close()
    {
        if(_fd>0)
        close(_fd);
    }
    ~FileOper()
    {
        
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};